import React, { ChangeEvent } from 'react';
import styles from './index.less';
import {
  Select,
  Input,
  DatePicker,
  Button,
  Table,
  Space,
  message,
  Form,
  Modal,
  Spin,
} from 'antd';
import { ExclamationCircleOutlined } from '@ant-design/icons';
import locale from 'antd/es/date-picker/locale/zh_CN';
import 'moment/locale/zh-cn';
import SaleForm from '@/components/saleForm/index';
import { IGoodsType, IColumns, IData, IProps, IState, IResponse, IFormItem } from './type';
import { FormInstance } from 'antd/es/form';
import moment from 'moment';
import { throttle } from '@/utils';
import { getServiceFormData, getServiceGoodsType, deleteServiceGoods, searchGoods, resetGoods } from '@/service/goods';

const { confirm } = Modal;
export default class Sub1 extends React.Component<IProps, IState> {
  state = {
    selectList: [], //商品种类数组
    formData: [], // 表格数值数组
    visible: false, //控制新增与修改弹出框的显隐
    selectKey: 0, // 表格中行的key
    spinning: false, // loading状态管理
    goodsInfo: {
      //修改时一行的值
      goodsCode: '',
      goodsName: '',
      norms: '',
      goodsType: '',
      unit: '',
    },
  };

  // loading效果加载
  spinLoading = (): void => {
    this.setState({
      spinning: true,
    });
  };

  // 失去loading效果
  spinStopLoading = (): void => {
    this.setState({
      spinning: false,
    });
  };

  // 修改
  modifyGoods = (record: IData): void => {
    this.state.formData.forEach((item: IData, i) => {
      if (item.key === record.key) {
        this.setState({
          visible: true,
          selectKey: record.key!,
          goodsInfo: item,
        });
      }
    });
  };

  // 删除弹框
  showConfirm = (key: number): void => {
    const _this = this;
    confirm({
      title: '确认删除',
      icon: <ExclamationCircleOutlined />,
      cancelText: '取消',
      okText: '确定',
      onOk() {
        _this.setState({
          spinning: true,
        });
        _this.deleteFinish(key);
      },
      onCancel() {
        console.log('取消');
      },
    });
  };

  // 删除元素
  deleteGoods = (key: number): void => {
    this.showConfirm(key);
  };

  // 请求删除元素的接口
  deleteFinish = (key: number): void => {
    deleteServiceGoods({key}).then((res: IResponse) => {
      if(res && res.code == 200) {
        this.getFormData();
        this.spinStopLoading();
      }
    });
  };

  // 新增按钮
  handleVisible = (): void => {
    this.setState({
      visible: true,
      selectKey: 0,
    });
  };

  
  // 请求搜索接口
  search = (): void => {
    this.spinLoading();
    this.formRef.current?.validateFields().then((res: IFormItem) => {
      let timeArr: Array<number> = [];
      res.picker?.forEach((item: moment.Moment, i: number) => {
        timeArr.push(moment(item).valueOf());
      });
      searchGoods({
        goodsType: res.norms,
        goodsName: res.name,
        time: timeArr,
      }).then((response: IResponse) => {
        if (!response.data!.length) {
          message.warning('当前搜索条件不存在表格内容！请重新选择');
        }
        res && this.setState({
          formData: (response.data as IData[]),
          spinning: false,
        });
      });
    });
  };

  onFinish = () => {};

  // 给 form 定义 ref
  formRef = React.createRef<FormInstance>();

  // 重置按钮操作
  resetField = (): void => {
    this.spinLoading();
    this.formRef.current?.resetFields();
    resetGoods().then((res: IResponse) => {
      if (res && res.code == 200) {
        this.getFormData();
        this.spinStopLoading();
      }
    });
  };

  // 请求表格数据
  getFormData = (): void => {
    getServiceFormData().then((res: IResponse) => {
      res && this.setState({
        formData: (res.data as IData[]),
      });
    });
  };

  // 请求商品种类接口
  getGoodsType = (): void => {
    getServiceGoodsType().then((res: IResponse) => {
      res && this.setState({
        selectList: (res.data as IGoodsType[]),
      });
    });
  };
  // 组件挂载时生命周期
  componentDidMount() {
    // 请求商品种类接口
    this.getGoodsType();

    // 请求表格数据
    this.getFormData();
  }

  render(): React.ReactNode {
    const { Option } = Select;
    const { RangePicker } = DatePicker;
    const columns: IColumns[] = [
      {
        title: '商品编码',
        dataIndex: 'goodsCode',
        align: 'center',
      },
      {
        title: '商品名称',
        dataIndex: 'goodsName',
        align: 'center',
      },
      {
        title: '商品规格',
        dataIndex: 'norms',
        align: 'center',
      },
      {
        title: '商品类别',
        dataIndex: 'goodsType',
        align: 'center',
      },
      {
        title: '单价',
        dataIndex: 'unit',
        align: 'center',
      },
      {
        title: '创建时间',
        dataIndex: 'time',
        align: 'center',
        render: (text: number) => {
          let now = new Date(text);
          // let y = now.getFullYear();
          // let mm = now.getMonth() + 1;
          // let d = now.getDate();
          // let h = now.getHours();
          // let minute = now.getMinutes();
          // let s = now.getSeconds();
          // return `${y}-${mm}-${d} ${h}:${minute}:${s}`;
          return moment(now).format('YYYY-MM-DD HH:mm:ss');
        },
      },
      {
        title: '操作',
        key: 'action',
        render: (text: IData, record: IData) => {
          //但是这里很奇怪，这里的text和record的值是一样的
          return (
            <Space size="middle">
              <a onClick={() => this.modifyGoods(record)}>修改</a>
              <a onClick={() => this.deleteGoods(record.key!)}>删除</a>
            </Space>
          );
        },
      },
    ];

    const { formData, visible, selectKey, selectList, goodsInfo, spinning } =
      this.state;
    const toSaleFormObj = {
      visible,
      selectKey,
      selectList,
      spinning,
      ...goodsInfo,
    };
    return (
      <Spin tip="加载中" spinning={spinning}>
        <div className={styles.saleContainer}>
          <h3>商品管理</h3>
          <div className={styles.searchDiv}>
            <Form
              name="form"
              style={{ padding: '24px 0' }}
              layout="inline"
              onFinish={this.onFinish}
              ref={this.formRef}
            >
              <Form.Item name="norms">
                <Select
                  placeholder="请选择商品种类"
                  style={{ width: 180, marginRight: 30 }}
                >
                  {this.state.selectList.map((item: IGoodsType) => {
                    return (
                      <Option value={item.type} key={item.id}>
                        {item.type}
                      </Option>
                    );
                  })}
                </Select>
              </Form.Item>
              <Form.Item name="name">
                <Input
                  placeholder="请输入商品名称"
                  style={{ width: 200, marginRight: 30 }}
                />
              </Form.Item>
              <Form.Item name="picker">
                <RangePicker style={{ marginRight: 30 }} locale={locale} />
              </Form.Item>
              <Form.Item>
                <Button
                  type="primary"
                  onClick={this.search}
                  style={{ marginRight: '30px' }}
                >
                  搜索
                </Button>
                <Button onClick={this.resetField}>重置</Button>
              </Form.Item>
            </Form>
          </div>
          <Button
            type="primary"
            style={{ margin: '0 0 30px 0' }}
            onClick={this.handleVisible}
          >
            新增
          </Button>
          <SaleForm
            {...toSaleFormObj}
            getFormData={this.getFormData}
            handleCancel={() => this.setState({ visible: false })}
          ></SaleForm>
          <Table
            columns={columns}
            dataSource={formData}
            style={{ width: '100%' }}
          />
        </div>
      </Spin>
    );
  }
}
